#include <stdlib.h>
#include <stdio.h>
#include <opencv2/opencv.hpp>
#include <opencv/highgui.h>
#include <time.h>

using namespace cv;

int main(int argc, char **argv)
{
  /* initialize camera */
  VideoCapture capture = VideoCapture(0);
  Mat frame;
  int key = 0;

  if(!capture.isOpened()) {
    fprintf( stderr, "Cannot open initialize webcam!\n");
    return 1;
  }

  cvNamedWindow( "result", CV_WINDOW_AUTOSIZE);
  clock_t start = clock();
  int frame_count = 0;
  
  while( key != 'q'){
    /* get a frame */
    frame_count++;
    if(!capture.read(frame)) {
      continue;
    }

    vector<uchar> buf;
    if(!imencode("*.jpg",frame,buf)) {
      break;
    }
    frame = imdecode(buf,1);

    /* always check */
    //if (!frame) break;

    /* display current frame */
    imshow("result", frame);
    //cvShowImage( "result", frame);

    /* exit if user press 'q' */
    key = cvWaitKey(1);
    //    printf("Frame Count: %d\n", frame_count);
    printf("%f\n", ((double)CLOCKS_PER_SEC*frame_count/((clock() - start))));
    fflush(stdout);
  }

  /* free memory */
  cvDestroyWindow( "result" );

  return 0;
}
